# -*- coding: utf-8 -*-
import telnetlib,time,sqlite3,MySQLdb
from threading import Thread
from Queue import Queue
from time import sleep,time

# 登录
def login():
	print tn.read_until("name:",1)
	tn.write("r")
	tn.read_until("r",1)
	tn.write("o")
	tn.read_until("o",1)
	tn.write("o")
	tn.read_until("o",1)
	tn.write("t")
	tn.read_until("t",1)
	tn.write("\r\n")
	print tn.read_until("assword:",1)
	tn.write("a")
	tn.read_until("*",1)
	tn.write("d")
	tn.read_until("*",1)
	tn.write("m")
	tn.read_until("*",1)
	tn.write("i")
	tn.read_until("*",1)
	tn.write("n")
	tn.read_until("*",1)
	tn.write("\r\n")
	print tn.read_until("->",1)

def telnetdo(HOST):
	# HOST="172.17.124.51"
	# USER="root"
	# PASS="admin"
	try:
		print "Connecting to "+HOST
		tn.open(HOST)
	except:
		print "Connect Error!"
		return
	login()
	# tn.write(":save-config;\r\n")
	# print tn.read_until("Succeed",5)
	tn.write("reboot\r\n")
	print tn.read_until('Are you sure to reboot system?("Y" or Other)',5)
	tn.write("Y\r\n")
	# conn.execute("update rnd set bSaved=1 where ndip='"+HOST+"'")
	# conn.commit()
	tn.close()

# 从mysql的rnd表取ndip数据
conn=MySQLdb.connect(host="172.16.100.31",user="root",passwd="admin",db="rainbow_3_0")
cursor=conn.cursor()
# cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr desc limit 10")
cursor.execute("select dscfgnwipaddr from rnd order by dscfgnwipaddr")
nds=cursor.fetchall()
cursor.close()
conn.close()
print len(nds)
tn = telnetlib.Telnet()
#q是任务队列
#NUM是并发线程总数
#JOBS是有多少任务
q = Queue()
NUM = 3
l=[]
#具体的处理函数，负责处理单个任务
def do_somthing_using(arguments):
	n={}
	n["ndip"]=arguments[0]
	try:
		# print "Connecting to "+arguments[0]
		tn.open(arguments[0],23,2)
		n["bAlive"]="1"
	except:
		print "Connect Error!"+arguments[0]
		n["bAlive"]="0"
	# print n
	l.append(n)

	
#这个是工作进程，负责不断从队列取数据并处理
def working():
	while True:
		arguments = q.get()
		do_somthing_using(arguments)
		q.task_done()
start=time()
#fork NUM个线程等待队列
for i in range(NUM):
	t = Thread(target=working)
	t.setDaemon(False)
	t.start()
#把JOBS排入队列
for i in nds:
	q.put(i)
#等待所有JOBS完成
q.join()
print time()-start
print "all jobs have done"
# print l
print "ready to saving data..."	
	
# 保存到sqlite
conn=sqlite3.connect(r'lkt.db3')
conn.text_factory = str
conn.execute("update rnd set bExist=0")

print len(l)
for x in l:
	# print x
	ndip=conn.execute("select ndip from rnd where ndip='"+x["ndip"]+"'").fetchone()
	if ndip:
		sql="update rnd set bAlive="+x["bAlive"]+",bExist=1 where ndip='"+x["ndip"]+"'"
	else:
		sql="insert into rnd(ndip,snmp0,snmp1,bAlive) values('"+x["ndip"]+"','','',"+x["bAlive"]+")"
	# print sql
	conn.execute(sql)
print "commit data to sqlite"
conn.commit()
conn.close()
del tn
